package cn.littlehx.myweb.service.Impl;

import cn.littlehx.myweb.dao.IUserDao;
import cn.littlehx.myweb.domain.User;
import cn.littlehx.myweb.service.IUserService;
import cn.littlehx.myweb.service.utils.MyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserServiceImpl extends ServiceImpl<IUserDao,User> implements IUserService {

    @Autowired
    private IUserDao IUserDao;
    @Autowired
    private MyUtils myUtils;

    /**
     * 对密码进行MD5加密,后期需要升级
     * @param entity
     * @return
     */
    @Override
    public boolean save(User entity) {
//        判断是否有相同邮箱的
        User user = this.selectByEmail(entity.getEmail());
        if(user == null){
//            String md5Passwd = DigestUtils.md5DigestAsHex(entity.getPassword().getBytes(StandardCharsets.UTF_8));
//            entity.setPassword(md5Passwd);
            String md5Passwd = myUtils.encode(entity.getPassword());
            entity.setPassword(md5Passwd);
            return super.save(entity);
        }
        else {
            return false;
        }


    }

    /**
     * 通过邮箱查找用户
     * @param email
     * @return
     */
    public User selectByEmail(String email) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email);
        List<User> userList = IUserDao.selectList(queryWrapper);
        if(userList.isEmpty()){
            return null;
        }else {
            return userList.get(0);
        }
    }

    /**
     * 通过邮箱和密码进行查询
     * @param email
     * @param password
     * @return
     */
    public User selectByEmailAndPassword(String email, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        String encodePassword = myUtils.encode(password);
        queryWrapper.eq(User::getEmail, email);
        queryWrapper.eq(User::getPassword,encodePassword);
        List<User> userList = IUserDao.selectList(queryWrapper);
        if(userList.isEmpty()){
            return null;
        }else {
            return userList.get(0);
        }
    }

    @Override
    public boolean updateById(User entity) {
        //进行密码加密
        String encode = myUtils.encode(entity.getPassword());
        entity.setPassword(encode);
        return super.updateById(entity);
    }
}
